/* 
    Based on function found on php.net
    
    131 dot php at cloudyks dot org
    20-Mar-2008 01:34 
    rp like, working with absolute/relative path & a little bit shorter :p 

*/
function rp(path){
    var out = new Array(); 
    var input = path.split("/");
    var fold = "";
    for(var i = 0; i < input.length; i++){ 
        fold = input[i];
        if (fold=='' || fold=='.') continue; 
        if (fold=='..' && i>0 && out[out.length-1]!='..') out.pop()
        else out[out.length] = fold; 
    }
    return out.join('/'); 
}

/**
    * File manager class
    */
var fileManager = {
    
    dir : "",
    type : "file",
    
    selectedFiles : new Array(),
    selectedFilesString : "",
    selected : null,
    
    cache : new Array(),
    treeCache : new Array(),
    window : false,

    preview : function(path){
        window.open(Cyfy.getSourcePath("files/" + fileManager.dir + path), "fMPreview", "width=640,height=480,resizable=yes,left=0,top=0,scrollbars=yes");
    },
    
    deleteSelected : function()
    {
        var send = "";
        for(var i = 0; i< fileManager.selectedFiles.length; i++)
        {
            file = fileManager.selectedFiles[i];
            send += "files[]=" + file + "&";
        }
        send += "prefixDirectory=" + fileManager.dir;
        
        Cyfy.ajax("FileManager", "deleteFiles", "", send, "fileManager.readDir(fileManager.dir, true);");
    },
    
    chmodSelected : function()
    {
        var send = "";
        for(var i = 0; i< fileManager.selectedFiles.length; i++)
        {
            file = fileManager.selectedFiles[i];
            send += "files[]=" + file + "&";
        }
        send += "prefixDirectory=" + fileManager.dir;
        
        Cyfy.ajax("FileManager", "chmodFiles", "", send);
    },
    
    treeDir : function(dir, $obj){
        if($obj.parent().next().hasClass("child")){
            // closing
            $obj.text("+");
            $obj.parent().next().remove();
        }else{
            // opening
            $obj.text("-");
            var cached = fileManager.treeCache["c" + dir];
            if(cached){
                if(cached!="<ul>\n</ul>\n"){
                    var place = $obj.parent().after("<li class=\"child\">" + cached + "</li>");
                }else{
                    $obj.remove();
                }
            }else{
                $.ajax({
                    type: "POST",
                    url: Cyfy.getSourcePath('ajax.php'),
                    data: "module=FileManager&ajax=treeDir&dirt=" + dir,
                    async: true,
                    dataType: "json",
                    success: function(data){
                        fileManager.treeCache["c" + dir] = data.text;
                        if(data.text!="<ul>\n</ul>\n"){
                            var place = $obj.parent().after("<li class=\"child\">" + data.text + "</li>");
                        }else{
                            $obj.remove();
                        }
                    }
                });
            }
        }
    },
     
    readDir : function(dir, force){
        dir = rp(dir) + "/";
        if(dir == "/"){
            dir = "";
        }
        if(fileManager.cache["c" + dir] && !force){
            // cached
            fileManager.dir = dir;
            $("#fileManagerFiles").html(fileManager.cache["c" + dir]);
            fileManager.reset();

        }else{
            // not cached
            $.ajax({
                type: "POST",
                url: Cyfy.getSourcePath('ajax.php'),
                data: "module=FileManager&ajax=readDir&dir=" + dir,
                async: true,
                dataType: "json",
                success: function(data){
                    if(data.messages){
                        cyfySetMessages(data.messages);
                    }
                    if(data.success == true){
                        $("#fileManagerFiles").html(data.text);
                        fileManager.cache["c" + dir] = data.text;
                        fileManager.dir = dir;
                        fileManager.reset();
                    }
                }
            });
        }
        
    },

    reset : function(){

        /* BOTH */
        // updates dir
        $("#fileManagerPath").attr("value", fileManager.dir);
        $("#fileUploadFormDirectory").attr("value", fileManager.dir);
        $("#makeDirectoryFormDirectory").attr("value", fileManager.dir);
        this.selectedFiles = new Array();
        this.selectedFilesString = '';
        
        if(fileManager.dir)
        {
            window.location.hash = "#" + fileManager.dir;
        }
        else 
        {
            window.location.hash = "#/";
        }
        
        
        /* WINDOW ONLY */
        
        if(fileManager.window){

            // disable text selecting
            $("#fileManagerFilesTable").find("tr").each(function()
            {
                $(this).attr('unselectable', 'on').css('-moz-user-select', 'none').each(function() { 
                   this.onselectstart = function() { return false; };
                });
            });
            
            // selecting
            $("#fileManagerFilesTable").find("tr").click(function()
            {
                $("#fileManagerPreviewButton").remove();
                
                $(fileManager.selected).removeClass("ui-selected");
                $(this).addClass("ui-selected");
                fileManager.selected = this;
                
                var ext = $(fileManager.selected).find(".ext").text();
                var filename = $(fileManager.selected ).find(".filename").text();
                $("#fileManagerPreviewFilename").text(filename);
                if(isImageExt(ext)){
                    $("#fileManagerPreviewImage").attr("src", Cyfy.getSourcePath("files/" + fileManager.dir + filename));
                    $("#fileManagerPreviewFilename").after("<input id=\"fileManagerPreviewButton\" onclick=\"FileBrowserDialogue.mySubmit(" + fileManager.dir + filename + "); return false;\" type=\"submit\" value=\"OK\" />");
                    $("#fileManagerPreviewButton").click(function(){
                        FileBrowserDialogue.mySubmit(fileManager.dir + filename);
                    });
                }else{
                    if(fileManager.type == "file"){
                        $("#fileManagerPreviewImage").attr("src", Cyfy.getSourcePath(("modules/FileManager/icons/64/file.png")));
                        $("#fileManagerPreviewFilename").after("<input id=\"fileManagerPreviewButton\" type=\"submit\" value=\"OK\" />");
                        $("#fileManagerPreviewButton").click(function(){
                            FileBrowserDialogue.mySubmit(fileManager.dir + filename);
                        });
                    }else{
                        $("#fileManagerPreviewImage").attr("src", Cyfy.getSourcePath("modules/FileManager/icons/64/folder.png"));
                    
                    }
                }
            });
            
            // dblclick on the file
            $("#fileManagerFilesTable tr").dblclick(function(){
                var filename = $(this).find(".filename").text();
                var ext = $(this).find(".ext").text();
                if(isImageExt(ext)){
                    FileBrowserDialogue.mySubmit(fileManager.dir + filename);
                }
            });

        /* NORMAL */
        }else{
            
            // SELECTABLE
            $("#fileManagerFilesTable").selectable({
                filter: 'tr',
                start : function(event, ui)
                {
                    fileManager.selectedFiles = new Array();
                    fileManager.selectedFilesString = "";
                },
                stop: function(event, ui) {
                    
                    $("#fileManagerFilesTable .ui-selected").each(function(){
                        var filename = $(this).find(".filename").text();
                        if(filename == "..") return;
                        fileManager.selectedFiles.push(filename);
                        fileManager.selectedFilesString += filename + " ";
                    });
                }
            });
        
            // open file on dblclick
            $(".fileManagerFile").dblclick(function(){
                var ext = $(this).find(".ext").text();
                if(isImageExt(ext)){
                    fileManager.preview($(this).find(".filename").text());
                }
            });
        }
        
        // BOTH
        
        // open dir on dblclick
        $(".fileManagerFolder td").dblclick(function(){
            fileManager.readDir(fileManager.dir + $(this).parent().find(".filename").text());
        });
        
        $("#fileManagerFilesTable").attr("cellspacing", "0");
    }, 
    
    colorize:function($obj){
        $(".tree-selected").removeClass("tree-selected");
        $obj.addClass("tree-selected");    
    }
}

function isImageExt(ext){
    if(ext == "jpeg" || ext == "jpg" || ext == "png" || ext == "gif"){
        return true;
    }
    return false;
}

$(document).ready(function(){
    fileManager.type = $("#fileManagerType").attr("value");
    
    // if some path
    var hash = window.location.hash;
    if(hash){
        fileManager.readDir(hash.substr(1));
    }else{
        fileManager.reset();
    }
    
    $("#fileManagerPathForm").submit(function(){
        fileManager.readDir($("#fileManagerPath").attr("value"));
        return false;
    });
});
